package com.kk.goGame.controller;


import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.kk.goGame.entity.Orders;
import com.kk.goGame.service.IOrdersService;
import com.kk.goGame.service.impl.OrdersServiceImpl;
import com.kk.goGame.utils.AlipayUtils;
import com.kk.goGame.utils.R;
import com.qf.framwork.annotation.RequestParams;
import com.qf.framwork.base.BaseServlet;
import com.qf.framwork.utils.PropertiesUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author kk
 * @since 2023-02-14
 */
@WebServlet("/orders")
public class OrdersController extends BaseServlet {
    private IOrdersService ordersService = new OrdersServiceImpl();

    public R createOrders(@RequestParams("id") Integer id, @RequestParams("price")Integer price) {
        String orders = ordersService.createrOders(id,price);
        return R.ok("订单创建成功",orders);
    }

    public String pay(@RequestParams("ordersId")String oid){
        System.out.println("请求获取到的oid是"+oid);
        Orders orders = ordersService.checkColumn("oid",oid);
        System.out.println("payOrders:"+orders);

        //调用支付宝的支付接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步通知地址 - 支付结果的回调地址[重要]
        request.setNotifyUrl(PropertiesUtils.getProperties("outIP")+"/orders?method=payResult");
        request.setReturnUrl("http://127.0.0.1:8848/goGame/gogame/index.html");//同步访问地址 - 支付结束后跳转到什么地方
        //封装请求体
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orders.getOid());
        bizContent.put("total_amount", orders.getPrice());
        bizContent.put("subject", "欢乐豆充值");
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());

        //发送支付页面请求
        AlipayTradePagePayResponse response = null;
        try {
            response = AlipayUtils.getAlipayClient().pageExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            //获取支付页面
            String payPage = response.getBody();
            return payPage;
        } else {
            System.out.println("调用失败");
        }

        return "<html>支付宝的访问异常！</html>";
    }

    /**
     * 支付结果的回调
     * @return
     */
    public String payResult(HttpServletRequest request){
        //根据请求对象获取所有参数列表
        Map<String, String[]> parameterMap = request.getParameterMap();
        //方式一：正常
//        //转换Map集合 - Map<String, String[]> -> Map<String, String>
//        Map<String, String> paramsMap = new HashMap<>();
//        //循环上面的Map
//        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
//            if (entry.getKey().equals("sign") || entry.getKey().equals("sign_type")) continue;
//            paramsMap.put(entry.getKey(), entry.getValue()[0]);
//        }

        //方式二：stream流+lambda表达式
        Map<String, String> paramsMap = parameterMap.entrySet().stream()
                .filter(entry -> !entry.getKey().equals("method"))
                .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()[0]));

        for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
            System.out.println(entry.getKey() + "--" + entry.getValue());
        }

//        Map<String, String> paramsMap = ... //将异步通知中收到的所有参数都存放到map中
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap,
                    PropertiesUtils.getProperties("aliPublic.key"),
                    "UTF-8",
                    "RSA2"); //调用SDK验证签名
            if(signVerified){
                // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
                System.out.println("请求结果验签成功！" + paramsMap.get("out_trade_no") + " " + paramsMap.get("trade_status"));

                //获取交易状态
                String status = paramsMap.get("trade_status");
                if (status.equals("TRADE_SUCCESS") || status.equals("TRADE_FINISHED")) {
                    //支付成功
                    System.out.println("支付成功，开始修改数据库");
                    //修改订单状态
                    String oid = paramsMap.get("out_trade_no");
                    Orders orders = new Orders();
                    orders.setOid(oid);
                    orders.setStatus(1);
                    ordersService.updateOrdersStatus(orders);
                }
            }else{
                // TODO 验签失败则记录异常日志，并在response中返回failure.
                System.out.println("请求结果验签失败！");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "success";
    }
    public R tongjiPrice(@RequestParams("uid") Integer uid){
        Map<Date, Integer> map = ordersService.tongjiPrice(uid);
        List list1 = new ArrayList();
        List list2 = new ArrayList();
        for (Map.Entry<Date, Integer> dateIntegerEntry : map.entrySet()) {
            list1.add(dateIntegerEntry.getKey().toString().replace(" 00:00:00",""));
            list2.add(dateIntegerEntry.getValue());
        }
        List list = new ArrayList();
        list.add(list1);
        list.add(list2);
        return R.ok(null,list);
    }

    public R getAll(@RequestParams("uid") Integer uid){
        return R.ok(null,ordersService.getAll(uid));
    }
}
